package cn.edu.zut.hhr.interceptor;

import cn.edu.zut.hhr.entity.User;
import cn.edu.zut.hhr.service.UserService;
import cn.edu.zut.hhr.utils.RedisUtil;
import cn.edu.zut.hhr.utils.UserUtil;
import cn.edu.zut.hhr.vo.RestResponse;
import com.alibaba.fastjson.JSON;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
@Order(10000)
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        User user = UserUtil.currentUser();
        if(user != null){
            return true;
        }
        RestResponse restResponse = RestResponse.fail(401,"登录已过期,请重新登录");
        response.setContentType("application/json;charSet=utf-8");
        response.getWriter().print(JSON.toJSONString(restResponse));
        return false;
    }
}
